//模拟实现优先级队列
import java.util.Arrays;

public class PriorityQueue {
    public int[] elem;
    public int usedSize;

    public PriorityQueue() {
        this.elem = new int[10];
        this.usedSize = 0;
    }

    /**
     * 建堆的时间复杂度：
     *
     * @param array
     */
    public void createHeap(int[] array) {
        if(array.length > this.elem.length) {
            elem = Arrays.copyOf(this.elem,array.length); //判断长度是否够
        }
        for (int i = 0; i < array.length; ++i) {
            elem[i] = array[i];  //将要排序的数组存到堆中
            usedSize++;
        }
        int parent = (usedSize-1-1)/2;
        for(int i = parent; i >= 0; --i) {
            shiftDown(i,usedSize);  //向下构建大根堆
        }
        System.out.println("  ");
    }

    /**
     *
     * @param root 是每棵子树的根节点的下标
     * @param len  是每棵子树调整结束的结束条件
     * 向下调整的时间复杂度：O(logn)
     */
    private void shiftDown(int root,int len) {
        int child = root * 2 + 1;
        while(child < len) {
            child = child + 1 < len && elem[child+1] > elem[child] ? child + 1 : child;
            if(elem[child] > elem[root]) {
                swap(child,root);
                root = child;
                child = root * 2 + 1;
            }
            else {
                break;
            }
        }
    }


    /**
     * 入队：仍然要保持是大根堆
     * @param val
     */
    public void push(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem,elem.length*2);  //满了就扩容
        }
        elem[usedSize] = val;
        shiftUp(usedSize);
        usedSize++;
    }

    private void shiftUp(int child) {
        int parent = (child-1)/2;
        while (elem[child] > elem[parent]) {
            swap(child,parent);
            child = parent;
            parent = (child-1)/2;
        }
    }

    public boolean isFull() {
        return usedSize == elem.length;
    }

    /**
     * 出队【删除】：每次删除的都是优先级高的元素
     * 仍然要保持是大根堆
     */
    public void pollHeap() {
        if(isEmpty()) {
            return;  //堆为空则直接返回
        }
        swap(0,usedSize-1);
        usedSize--;
        shiftDown(0,usedSize);
    }

    public boolean isEmpty() {
        return usedSize  == 0;
    }

    /**
     * 获取堆顶元素
     * @return
     */
    public int peekHeap() {
        if(!isEmpty()) {
            return elem[0];
        }
        return -1;
    }

    public void swap(int i, int j) {
        int temp = elem[i];
        elem[i] = elem[j];
        elem[j] = temp;
    }
}
